<template>
  <div>
    <el-button type="write" @click="AddOrders">新增</el-button>
    <el-button type="write" @click="ExportToExcel">导出</el-button>
    <!-- 添加文件选择器 -->
    <el-button type="write" @click="openFileSelector">导入</el-button>
    <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" />
    &nbsp;
    <!-- <el-button type="write" @click="Deletedorders">批量删除</el-button> -->

  </div>
  <h2 style="margin-left: 350px">生产订单明细列表</h2>
  <el-table :data="tableData" style="width: 100%" :loading="isLoading" @selection-change="handleSelectionChange"
    ref="tableRef">
    <el-table-column type="selection" width="55" />
    <el-table-column type="index" label="序号" width="70" />
    <el-table-column prop="documentsNum" label="生产订单编号" width="150" />
    <el-table-column prop="documentsName" label="生产订单主题" width="120" />
    <el-table-column prop="projectId" label="关联项目" width="120" :formatter="formatProjectId" />
    <el-table-column prop="productName" label="产品名称" width="150" />
    <el-table-column prop="personnel" label="制单人员" width="120" />
    <el-table-column prop="time" label="制单日期" width="120" :formatter="formatDate" />
    <el-table-column label="操作" min-width="300">
      <template #default="scoped">
        <el-button link type="warning" :icon="Edit" size="small" @click="Upd(scoped.row.documentsId)">修改</el-button>
        <el-button link type="danger" :icon="Delete" size="small" @click="Del(scoped.row.documentsId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-button @click="handleSelectAll">全选</el-button>
  <el-button @click="handleReverseSelect">反选</el-button>
  <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pagesize" :page-sizes="[15, 20, 25, 30]"
    :background="background" layout="total, sizes, prev, pager, next, jumper" :total="form.totalCount"
    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { Wread, Wwrite } from "@/axios/axiosHelper"
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue'

const router = useRouter();
const fileInput = ref<HTMLInputElement | null>(null);

// 定义分页表单数据
const form = reactive({
  pagesize: 15,
  pageIndex: 1,
  totalCount: 0,
  totalPage: 0,
});

// 定义表格数据
const tableData = ref([]);
// 定义分页背景
const background = ref(true);
// 定义加载状态
const isLoading = ref(false);
// 定义选中的行数据
const multipleSelection = ref([]);
// 定义选中的 documentsId 数组
const selectedDocumentsIds = ref<string[]>([]);
// 定义表格引用
const tableRef = ref(null);

// 假设的项目 ID 到中文的映射关系
const projectIdToChinese = {
  "1": "汽车零部件",
  "2": "医疗器械",
  "3": "生活用品",
  "4": "工程项目",
  // 其他映射关系...
};

//删除
const Del = (documentsId: any) => {
  console.log("查询需要删除数据的Id", documentsId);
  ElMessageBox.confirm(
    '确认删除吗？',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
   .then(() => {
      Wwrite.post("w-write/api/Orders/DelOrders", {
        documentsId: documentsId
      })
       .then(res => {
          if (res.data.code == 100) {
            ElMessage.success(res.data.msg);
            fetchOrders();
          }
          else {
            ElMessage.error(res.data.msg);
          }
        })
    })
   .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
};

// 打开文件选择器
const openFileSelector = () => {
  fileInput.value?.click();
};

// 处理文件选择变化
const handleFileChange = async () => {
  const file = fileInput.value?.files?.[0];
  if (file) {
    const formData = new FormData();
    formData.append('file', file);
    try {
      const res = await Wread.post("w-read/api/Orders/ImportExcel", formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      if (!res.data.code) {
        ElMessage.success("导入成功");
        fetchOrders();
      } else {
        ElMessage.error(res.data.msg);
      }
    } catch (error) {
      if (axios.isAxiosError(error)) {
        if (error.response) {
          ElMessage.error(`导入数据出错，状态码: ${error.response.status}`);
        } else if (error.request) {
          ElMessage.error('导入数据出错，无响应，请检查网络');
        } else {
          ElMessage.error('导入数据出错，请求配置有误');
        }
      } else {
        ElMessage.error('导入数据出错，请检查网络或联系管理员');
      }
      console.error('导入数据出错:', error);
    }
  }
};

// 修改后的导出方法
const ExportToExcel = async () => {
  try {
    const res = await axios.get("https://localhost:7271/api/Orders/ExportToExcel", {
      responseType: 'blob' // 设置响应类型为 blob
    });
    // 创建一个临时的 URL 对象
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    link.href = url;
    // 设置下载的文件名
    link.setAttribute('download', 'production_orders.xlsx');
    document.body.appendChild(link);
    link.click();
    // 释放 URL 对象
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
  } catch (error) {
    if (axios.isAxiosError(error)) {
      if (error.response) {
        ElMessage.error(`导出数据出错，状态码: ${error.response.status}`);
      } else if (error.request) {
        ElMessage.error('导出数据出错，无响应，请检查网络');
      } else {
        ElMessage.error('导出数据出错，请求配置有误');
      }
    } else {
      ElMessage.error('导出数据出错，请检查网络或联系管理员');
    }
    console.error('导出数据出错:', error);
  }
};

//修改
const Upd = (documentsId: any) => {
  router.push({
    path: '/UpdateOrder',
    query: { documentsId: documentsId }
  });
  console.log("获取的id为", documentsId)
};

// 封装获取订单数据的函数
const fetchOrders = async () => {
  isLoading.value = true;

  try {
    const res = await Wread.get("w-read/api/Orders/QueryOrders", {
      params: {
        pageIndex: form.pageIndex,
        pageSize: form.pagesize
      }
    });
    if (res.status === 200) {
      tableData.value = res.data.data;
      form.totalCount = res.data.totalCount;
      form.totalPage = res.data.totalPage;
    } else {
      ElMessage.error('请求数据失败，请稍后重试');
    }
  } catch (error) {
    if (axios.isAxiosError(error)) {
      if (error.response) {
        ElMessage.error(`请求数据出错，状态码: ${error.response.status}`);
      } else if (error.request) {
        ElMessage.error('请求数据出错，无响应，请检查网络');
      } else {
        ElMessage.error('请求数据出错，请求配置有误');
      }
    } else {
      ElMessage.error('请求数据出错，请检查网络或联系管理员');
    }
    console.error('请求数据出错:', error);
  } finally {
    isLoading.value = false;
  }

};

// 页面挂载时获取数据
onMounted(() => {
  fetchOrders();
});

// 处理关联详情按钮点击事件
const handleClick = () => {
  console.log('click');
};

// 处理每页显示数量变化
const handleSizeChange = (newSize: any) => {
  form.pagesize = newSize;
  fetchOrders();
};

// 处理当前页码变化
const handleCurrentChange = (newPage: any) => {
  form.pageIndex = newPage;
  fetchOrders();
};

// 格式化日期
const formatDate = (row: any, column: any, cellValue: any) => {
  const date = new Date(cellValue);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 格式化关联项目
const formatProjectId = (row: any, column: any, cellValue: any) => {
  return projectIdToChinese[cellValue] || cellValue;
};

// 处理行选择变化
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  selectedDocumentsIds.value = val.map(item => item.documentsId);
};

// 处理全选操作
const handleSelectAll = () => {
  tableRef.value?.toggleAllSelection();
  selectedDocumentsIds.value = tableData.value.map(item => item.documentsId);
};

// 处理反选操作
const handleReverseSelect = () => {
  tableData.value.forEach(row => {
    const isSelected = multipleSelection.value.some(item => item.documentsId === row.documentsId);
    tableRef.value?.toggleRowSelection(row, !isSelected);
  });
  selectedDocumentsIds.value = tableData.value.filter(row => !multipleSelection.value.some(item => item.documentsId === row.documentsId)).map(item => item.documentsId);
};

const AddOrders = () => {
  router.push({ path: '/CreateOrders' })
};
</script>